package com.kuangstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuangstudy.entity.State;
import com.kuangstudy.entity.StateDetail;
import com.kuangstudy.service.detail.StateDetailService;
import com.kuangstudy.service.state.StateService;
import com.kuangstudy.vo.R;
import com.kuangstudy.vo.StateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller //直接走我们的流输出 不会走视图解析器
public class StateController {
    @Autowired
    private StateService stateService;

    @Autowired
    private StateDetailService stateDetailService;
    /**
     * 根据ID跳到指定的明细页面
     *
     * @return ModelMap map 异步处理
     */
    @GetMapping("/state/{id}")
    public String findStates(@PathVariable("id") Integer id, ModelMap mapMap) {
        //1.根据id查询主题是否存在
        State state = stateService.getById(id);
        //2.如果存在就进入页面
        if (state != null) {
            //1.设置条件
            mapMap.put("id", id);
            return "state/detail";
        }
        //3.如果不存在就进入到错误页面 (统一异常处理和错误处理)
        return "redirect:/error";
    }


    /**
     * @Author Melody_LQ
     * @Date 2021/6/14 15:29
     * @Description 根据stateid查询统计和统计明细
     * @Param stateid:
     * @Return com.kuangstudy.vo.R
     * @Since version-1.0
     */
    @GetMapping("/state/detail")
    @ResponseBody
    public R getStateDetail(Integer stateid){
        if (StringUtils.isEmpty(stateid)) return R.error().code(601).message("没有找到对应主题");
        //1：根据stateid查询统计
        State state = stateService.getById(stateid);
        if (state == null) return R.error().code(601).message("没有找到对应主题");
        //2：根据stateid查询统计明细
        QueryWrapper<StateDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stateid",stateid);
        List<StateDetail> stateDetailList = stateDetailService.list(queryWrapper);
        //3：把state对象和statedetail组装到vo对象
        StateVo stateVo = new StateVo();
        BeanUtils.copyProperties(state,stateVo);
        stateVo.setStateDetailList(stateDetailList);
        //4：然后把vo用R统一返回出去
        return R.ok().data("stateVo",stateVo);
    }

}
